﻿using BassHelper;
using LrcHelper;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Xml;
using Test.ShowMessage;

namespace Test
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private FileInfo[] fis = null;
        private DispatcherTimer timer = new DispatcherTimer();

        public MainWindow()
        {
            InitializeComponent();

        }


        /// <summary>
        /// 创建歌词的几何图形
        /// </summary>
        /// <param name="text">歌词</param>
        /// <returns></returns>
        public Geometry CreateText(string text)
        {

            try
            {
                FormattedText ft =
                new FormattedText(
                    text,
                    CultureInfo.CurrentUICulture,
                    FlowDirection.LeftToRight,
                    new Typeface(new FontFamily(new Uri("pack://application:,,,/"), "./#Microsoft YaHei UI"), FontStyles.Normal, FontWeights.Bold, FontStretches.Normal),
                    25,
                    System.Windows.Media.Brushes.Black
                    );

                Geometry geometry = ft.BuildGeometry(new System.Windows.Point(0, 0));
                return geometry;
            }
            catch
            {
                return null;
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //获取配置的本地音乐文件夹并把里面的音乐文件给列出来

            string configPath = System.IO.Path.Combine(Environment.CurrentDirectory, "App.xml");
            XmlDocument doc = new XmlDocument();
            doc.Load(configPath);
            XmlNode xn = doc.SelectSingleNode("//path");
            DirectoryInfo di = new DirectoryInfo(xn.InnerText.Trim());
            fis = di.GetFiles("*.mp3", SearchOption.AllDirectories);
            //ShowPromptMessage spm = new ShowPromptMessage("测试一下啊!");

            //设置歌词颜色
            SetLrcColor();

            if (fis.Length != 0)
            {
                BassEngine be = BassEngine.Instance;
                be.TrackEnded += be_TrackEnded;

                ThreadPool.QueueUserWorkItem(new WaitCallback(play =>
                {
                    Play(fis[new Random().Next(fis.Length)]);
                }));
            }
        }

        void be_TrackEnded(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(play =>
            {
                Play(fis[new Random().Next(fis.Length)]);
            }));
        }

        private void SetLrcColor()
        {
            #region 设置歌词颜色
            System.Windows.Shapes.Path[] pa = new System.Windows.Shapes.Path[3];
            pa[0] = text1;
            pa[1] = text2;
            pa[2] = text3;
            foreach (var item in pa)
            {
                SolidColorBrush b = new SolidColorBrush(Color.FromArgb(250, 250, 250, 250));
                item.Fill = b;
                //  item.Data = CreateText("此处是歌词 此处是歌词 此处是歌词 ");
            }
            shadowEffect.Color = Color.FromArgb(250, 10, 10, 10);
            #endregion
        }

        private void Play(FileInfo fi)
        {

            #region 播放
            string songName = fi.Name.Substring(0, fi.Name.IndexOf("-"));
            string aName = fi.Name.Substring(fi.Name.IndexOf("-") + 1);
            Lyrics lrc = Helper.GetLyrics(aName, songName);
            BassEngine be = BassEngine.Instance;
            be.Volume = 0.618;
            //打开网络地址时并不是立即播放,是创建一个新的线程去获取文件流,如果拿到文件流的句柄,并且播放器为播放状态,则开始播放音乐
            //打开网络上的音乐文件时,对方服务器必须支持range定义,也就是支持断点续传功能,否则则无法进行播放
            //be.OpenMusic("https://pcs.baidu.com/rest/2.0/pcs/stream?method=download&access_token=3.dc2042e45b45a519496d08e08048ae2d.2592000.1370412604.3674552515-248414&path=%2Fapps%2F%E6%B5%8B%E8%AF%95%E5%BA%94%E7%94%A8%2Ffr.mp3");

            be.OpenMusic(fi.FullName);
            timer.Interval = TimeSpan.FromSeconds(1);
            be.Play();
            timer.Start();
            #endregion

            #region timer 动态的展示歌词

            timer.Tick += (sender1, e1) =>
            {
                if (lrc != null)
                {
                    if (be.IsPlaying)
                    {
                        TimeSpan timeLine = be.ChannelPosition;
                        TimeSpan lrcNext = lrc.SortedTimes.Find((thisOne) => { if (timeLine < thisOne)return true; else return false; });
                        if (!lrcNext.Equals(TimeSpan.Zero))
                        {
                            TimeSpan lrcNow;
                            if (lrc.SortedTimes.IndexOf(lrcNext) == 0)
                            {
                                lrcNow = lrc.SortedTimes[0];
                                lrcNext = lrc.SortedTimes[1];
                            }
                            else
                            {
                                lrcNow = lrc.SortedTimes[lrc.SortedTimes.IndexOf(lrcNext) - 1];
                            }
                            string lrcNowStr = lrc.TimeAndLyrics[lrcNow];
                            string lrcNextStr = lrc.TimeAndLyrics[lrcNext];
                            text1.Data = CreateText(lrcNowStr);
                            text2.Data = CreateText(lrcNextStr);
                            winAPI.NativeMethod.SetWindowPos(new WindowInteropHelper(this).EnsureHandle(), new IntPtr(-1), 0, 0, 0, 0, 0x0002 | 0x0001 | 0x0010 | 0x0200 | 0x0008);
                        }
                        else
                        {
                            lrc = null;
                        }
                    }
                }
            };
            #endregion
        }
    }
}
